#include "TrSocket.h"
#include "include/TrGlobal.h"

CTrSocket::CTrSocket()
{

}

void CTrSocket::setupSocketInit(QString ip, unsigned short port, QString ca)
{
    if(m_pSocket) return;

    m_pSocket = new QSslSocket(this);

    connect(m_pSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
    connect(m_pSocket, SIGNAL(encrypted()),
            this, SLOT(socketEncrypted()));
    connect(m_pSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(m_pSocket, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(sslErrors(QList<QSslError>)));
    connect(m_pSocket, SIGNAL(readyRead()),
            this, SLOT(socketReadyRead()));

    m_pSocket->setProtocol(QSsl::TlsV1_2OrLater);

    /* 由于是自签证，所以要设置根证书，用于验证服务器证书，否则客户端不信任服务器 */
    QList<QSslCertificate> certs = QSslCertificate::fromPath(ca);
    m_pSocket->setCaCertificates(certs);
    m_pSocket->setPeerVerifyDepth(QSslSocket::VerifyNone);

    /* 客户端链接服务器进行SSL握手，当进入加密模式后会发出Encrypted()信号 */
    m_pSocket->connectToHostEncrypted(ip, port);
}

void CTrSocket::updateEnabledState()
{
    qDebug() << __FUNCTION__;
}

void CTrSocket::secureConnect()
{
    qDebug() << __FUNCTION__;
}

void CTrSocket::socketStateChanged(QAbstractSocket::SocketState state)
{
    qDebug() << __FUNCTION__ << state;
}

void CTrSocket::socketEncrypted()
{
    qDebug() << __FUNCTION__;
}

void CTrSocket::socketReadyRead()
{
    QSslSocket* pSocket = static_cast<QSslSocket*>(sender());
    //QByteArray data = pSocket->readAll();


    packet p;
    memset(&p, 0, sizeof(p));

    p.header.cmd = Tr_RequestCommand::TR_CMD_REQUEST_DAYKLINE;
    strcpy_s(p.header.verison, sizeof(p.header.verison), "2.0.0");
    strcpy_s(p.data, sizeof(p.data), "version:2.0.0");
    strcpy_s(p.header.userinfo.InstrumentID, sizeof(p.header.userinfo.InstrumentID), "rb1910");

    QByteArray senData;
    senData.resize(sizeof(packet));
    memcpy(senData.data(), &p, sizeof(packet));

    qDebug() << sizeof(p) << sizeof(senData) << sizeof(packet);
    pSocket->write(senData);
    pSocket->flush();



}

void CTrSocket::sendData()
{
    qDebug() << __FUNCTION__;
}

void CTrSocket::socketError(QAbstractSocket::SocketError error)
{
    qDebug() << __FUNCTION__ << error;
}

void CTrSocket::sslErrors(const QList<QSslError> &errors)
{
    qDebug() << __FUNCTION__;
}

void CTrSocket::displayCertificateInfo()
{
    qDebug() << __FUNCTION__;
}

